package com.blockmeta.bbs.immodule.bean;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.util.DeepLinkUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Pattern;


public class IMCommonLib
{
    private static final long m_lDayOfTime = 86400000L;

    private static final Pattern matchPattern = Pattern.compile("<a href=['\"][^:]+://[^<>]+(user/)([^<>]+)['\"]>(\\$|@)([^<>]+)</a>");

    public static void fillContent(TextView textView, String content, Context context) {
        if (! TextUtils.isEmpty(content) && content.contains("://"))
        {
            content = content.replace("\n", "<br/>");

            Spanned spanned = Html.fromHtml(content);

            SpannableStringBuilder sp = new SpannableStringBuilder(spanned);

            URLSpan[] spans = sp.getSpans(0, sp.length(), URLSpan.class);
            if (spans != null)
            {
                for (URLSpan urlSpan : spans)
                {
                    ClickSpan mySpan = new ClickSpan(urlSpan.getURL(), context);
                    sp.setSpan(mySpan, sp.getSpanStart(urlSpan),
                            sp.getSpanEnd(urlSpan), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                    sp.removeSpan(urlSpan);
                }
            }

            Linkify.addLinks(sp, Linkify.WEB_URLS);

            spans = sp.getSpans(0, sp.length(), URLSpan.class);
            if (spans != null)
            {
                for (URLSpan urlSpan : spans)
                {
                    ClickSpan mySpan = new ClickSpan(urlSpan.getURL(), context);
                    sp.setSpan(mySpan, sp.getSpanStart(urlSpan),
                            sp.getSpanEnd(urlSpan), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                    sp.removeSpan(urlSpan);
                }
            }

            textView.setText(sp);
            textView.setMovementMethod(LinkMovementMethod.getInstance());

        }
        else
        {
            textView.setText(content);
        }
    }

    public static void fillContentNoSpan(TextView textView, String content) {
        if (! TextUtils.isEmpty(content) && content.contains("://"))
        {
            textView.setText(Html.fromHtml(content).toString());
        }else {
            textView.setText(content);
        }
    }

    public static String getContentNoSpan(String content){
        if (! TextUtils.isEmpty(content) && content.contains("://"))
        {
            return Html.fromHtml(content).toString();
        }else {
            return content;
        }
    }

    public static class ClickSpan extends ClickableSpan
    {
        private String m_Url;
        private Context mContext;

        public ClickSpan(String pUrl, Context context)
        {
            super();

            if (! TextUtils.isEmpty(pUrl))
            {
                pUrl = pUrl.replace("&quot;", "\"").replace("&amp;", "&")
                        .replace("&lt;", "<").replace("&gt;", ">");
            }

            this.m_Url = pUrl;
            this.mContext = context;
        }

        @Override
        public void updateDrawState(TextPaint ds)
        {
//			ds.setFakeBoldText(true);
            ds.setColor(Color.parseColor("#FF408FFD"));
            ds.setUnderlineText(false);
        }

        @Override
        public void onClick(View widget)
        {
            try {
                if (widget.getTag() != null) {
                    widget.setTag(null);
                    return;
                }

                if (TextUtils.isEmpty(m_Url))
                    return;

                LogUtils.d("author" + "click chat item deeplink" + m_Url);
                String regexUri = DeepLinkUtils.regexUri(m_Url);
                Uri uri = Uri.parse(regexUri);
                DeepLinkUtils.jumpToTarget(mContext, uri);
            } catch (Exception e) {
            }
        }
    }

    public static String getTimeDiff(long time)
    {
        try
        {
            Date targetDate = new Date(time);
            Date now = new Date();
            Date yesterday = new Date(now.getTime() - (24 * 60 * 60 * 1000));

            SimpleDateFormat format = new SimpleDateFormat("yyyy-D");
            String tTarget = format.format(targetDate);
            String tNow = format.format(now);
            String tYesterday = format.format(yesterday);

            String[] tTargetArr = tTarget.split("-");
            String[] tNowArr = tNow.split("-");
            String[] tYesterArr = tYesterday.split("-");

            int targetYear = Integer.parseInt(tTargetArr[0]);
            int targetDay = Integer.parseInt(tTargetArr[1]);
            int nowYear = Integer.parseInt(tNowArr[0]);
            int nowDay = Integer.parseInt(tNowArr[1]);
            int yesterYear = Integer.parseInt(tYesterArr[0]);
            int yesterDay = Integer.parseInt(tYesterArr[1]);

            if (nowYear == targetYear && nowDay == targetDay)
            {
                long diff = now.getTime() - targetDate.getTime();

                long diffMin = diff / (60 * 1000);
                long diffHour = diff / (60 * 60 * 1000);

                if (diffMin < 1)
                {
                    return (diff % (60 * 1000)) / 1000 + "s";
                }
                else if (diffHour < 1)
                {
                    return diffMin + "m";
                }
                else
                {
                    return diffHour + "h";
                }
            }
            else if (yesterYear == targetYear && yesterDay == targetDay)
            {
                format = new SimpleDateFormat( "HH:mm");
                return format.format(targetDate);
            }
            else if (nowYear == targetYear)
            {
                format = new SimpleDateFormat("MM/dd HH:mm");
                return format.format(targetDate);
            }
            else
            {
                format = new SimpleDateFormat("yyyy/MM/dd HH:mm");
                return format.format(targetDate);
            }
        }
        catch (Exception e)
        {

        }
        return "";
    }

    public static String getDisplayTime(long pTimeStamp, String timeFormat)
    {
        Calendar mCalendar = Calendar.getInstance();
        mCalendar.setTimeInMillis(pTimeStamp);
        String m_strTime = new SimpleDateFormat(timeFormat).format(pTimeStamp);
        if (mCalendar.get(Calendar.AM_PM) == Calendar.AM)
        {//上午
                m_strTime =  "上午 " + m_strTime;

        }
        else
        {//下午
               m_strTime = "下午 " + m_strTime;
        }
        return m_strTime;
    }

	/**
     *
     *
     * 需求：1、当天显示：hh:mm（24小时制）
     2、前1天显示：昨天
     3、前2-5天显示：星期X
     4、历史显示：
     今年：mm/dd
     历年：yy/mm/dd
     通过调用  IMCommonLib.convertTimeFormat(time, "hh:mm", "", "MM/dd", "yyyy/MM/dd")
     * @param pTime
     * @param pToday
     * @param pYesterday
     * @param pThisYear
     * @param pBeforeAYear
     * @return
     */
    public static String convertTimeFormat(long pTime, String pToday, String pYesterday, String pThisYear, String pBeforeAYear,boolean isChinese)
    {
        String tResult;
        String dateFormat = isChinese ? "yyyy-MM-dd" : "MM-dd-yyyy";


        Calendar now = Calendar.getInstance();
        Calendar time = Calendar.getInstance();
        time.setTimeInMillis(pTime);;

        Date date = time.getTime();

        int dayNow = now.get(Calendar.DAY_OF_YEAR);
        int dayTime = time.get(Calendar.DAY_OF_YEAR);

        if (now.get(Calendar.YEAR) != time.get(Calendar.YEAR))
        {
            if (pBeforeAYear == null || pBeforeAYear.length() == 0)
            {
                tResult = new SimpleDateFormat(dateFormat).format(date);
            }
            else
            {
                tResult = new SimpleDateFormat(pBeforeAYear).format(date);
            }
        }
        else if (dayNow - dayTime > 5)
        {
            if (pThisYear == null || pThisYear.length() == 0)
            {
                tResult = new SimpleDateFormat("MM-dd").format(date);
            }
            else
            {
                tResult = new SimpleDateFormat(pThisYear).format(date);
            }
        }
        else if (dayNow - dayTime > 1 && dayNow - dayTime <= 5)
        {
            if (pThisYear == null || pThisYear.length() == 0)
            {
                tResult = new SimpleDateFormat("MM-dd").format(date);
            }
            else
            {
                String[] weeks = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
                String[] englishWeeks = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};


                int week_index = time.get(Calendar.DAY_OF_WEEK) - 1;
                if(week_index<0){
                    week_index = 0;
                }

                tResult = isChinese ? weeks[week_index] : englishWeeks[week_index];
            }
        }
        else if (dayNow != dayTime)
        {
            if (pYesterday == null || pYesterday.length() == 0)
            {
                tResult = "昨天";
            }
            else
            {
                tResult = new SimpleDateFormat(pYesterday).format(date);
            }
        }
        else
        {
            if (pToday == null || pToday.length() == 0)
            {
                tResult = "今天";
            }
            else
            {
                tResult = new SimpleDateFormat(pToday).format(date);
//                tResult = getDisplayTime(pTime, pToday);
            }
        }

        return tResult;
    }

    public static void copyToClipboard(String pTxt)
    {
        if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
            android.text.ClipboardManager clipboard = (android.text.ClipboardManager) BaseApp.getApp().getSystemService(Context.CLIPBOARD_SERVICE);
            clipboard.setText(pTxt);
        } else {
            android.content.ClipboardManager clipboard = (android.content.ClipboardManager) BaseApp.getApp().getSystemService(Context.CLIPBOARD_SERVICE);
            android.content.ClipData clip = android.content.ClipData.newPlainText("Copy", pTxt);
            clipboard.setPrimaryClip(clip);
        }
    }
}
